﻿using System;
using System.Diagnostics;
using System.Drawing;
using System.Windows.Forms;
using Microsoft.SqlServer.Management.UI.VSIntegration;
using Microsoft.SqlServer.Management.UI.VSIntegration.ObjectExplorer;
using SsmsAddin.Properties;

namespace SsmsAddin
{
    ///<summary>
    ///</summary>
    public partial class frmSvnStatus : UserControl
    {
        private readonly ListViewColumnSorter _lvwColumnSorter;
        private ImageList _imageList;

        ///<summary>
        ///</summary>
        public frmSvnStatus()
        {
            InitializeComponent();
            _lvwColumnSorter = new ListViewColumnSorter();
            listViewResults.ListViewItemSorter = _lvwColumnSorter;

        }

        private void frmSvnStatus_Load(object sender, EventArgs e)
        {

            _imageList = new ImageList();
            Bitmap statusGlyphs = Resources.StatusGlyphs;
            _imageList.ImageSize = new Size(8, statusGlyphs.Height);
            statusGlyphs.MakeTransparent(statusGlyphs.GetPixel(0, 0));
            _imageList.Images.AddStrip(statusGlyphs);
            listViewResults.SmallImageList = _imageList;
            UpdateObjectExplorerInfo();
            var service = (IObjectExplorerEventProvider)ServiceCache.GetObjectExplorer().GetService(typeof(IObjectExplorerEventProvider));
            service.SelectionChanged += ProviderSelectionChanged;

            UpdateObjectExplorerInfo();
            ObtainStatus();
        }

        private void ProviderSelectionChanged(object sender, NodesChangedEventArgs args)
        {
            UpdateObjectExplorerInfo();
            ObtainStatus();
        }

        private void ObtainStatus()
        {
            var str = Properties.Settings.Default.LocalSvnPath;
            str = str.Replace("{database}", Utils._DBNode.dbName);
            str = str.Replace(@"{object}\", "");
            str = str + "*.*";
            listViewResults.Items.Clear();
            var process = new Process
                          {
                              EnableRaisingEvents = false, StartInfo = {CreateNoWindow = true, FileName = "svn.exe", Arguments = string.Format("status --username {1} {0}", str, Properties.Settings.Default.UserName), UseShellExecute = false, RedirectStandardOutput = true}
                          };
            process.Start();
            while (!process.StandardOutput.EndOfStream)
            {
                var str2 = process.StandardOutput.ReadLine();
                if ((str2.Length < 8) || (str2.Substring(0, 1) == "-"))
                {
                    continue;
                }

                var str4 = str2.Substring(8);
                const string str5 = @"\";
                var ch = str5[0];

                var strArray = str4.Split(new char[] { ch });
                var strArray2 = Properties.Settings.Default.LocalSvnPath.Split(new [] { ch });

                if (strArray.Length < strArray2.Length)
                {
                    continue;
                }

                var str6 = strArray[4].Replace(".sql", "");
                var str7 = str2.Substring(0, 1);

                string text;
                int imageIndex;
                switch (str7)
                {
                    case "D":
                        goto Label_01BD;
                    case "M":
                        goto Label_01C9;
                    case "A":
                        imageIndex = 13;
                        text = "Add";
                        break;
                    case "?" :
                        imageIndex = 7;
                        text = "Unversionned File";
                        break;
                    default :
                        goto Label_01C9;

                }
                goto Label_01FC;

            Label_01BD:
                imageIndex = 3;
                text = "Delete";
                goto Label_01FC;
            Label_01C9:
                if (str2.Substring(5, 1) == "K")
                {
                    imageIndex = 10;
                    text = "Locked & Modified";
                }
                else
                {
                    imageIndex = 9;
                    text = "Locked & Unmodified";
                }
            Label_01FC:
                if (imageIndex <= 0) continue;
                var item = listViewResults.Items.Add(strArray[3].ToLower() == "script" ? str6 : str6.ToLower(), imageIndex);

                item.SubItems.Add(strArray[3]);
                item.SubItems.Add(text);
            }

            // resize column to the content
            foreach (ColumnHeader col in listViewResults.Columns)
            {
                col.AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent);
            }

        }

        private void UpdateObjectExplorerInfo()
        {
            Utils.UpdateObjectExplorerInfo();
            toolStripLabelServer.Text = Utils._DBNode.serverName;
            toolStripLabelDatabase.Text = Utils._DBNode.dbName;
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            var str = string.Empty;
            foreach (ListViewItem item in this.listViewResults.SelectedItems)
            {
                if (str != string.Empty)
                {
                    str = str + "*";
                }
                str = str + Utils._GetFilePath(item.SubItems[1].Text, item.SubItems[0].Text);
            }
            Utils.execSvnCommand(Utils.svnCommand.scCommit, str);
        }

        private void listViewResults_DoubleClick(object sender, EventArgs e)
        {
            Process.Start(Utils._GetFilePath(listViewResults.SelectedItems[0].SubItems[1].Text, listViewResults.SelectedItems[0].SubItems[0].Text));
        }

        private void listViewResults_ItemActivate(object sender, EventArgs e)
        {

        }

        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            var str = Utils._GetFilePath(listViewResults.SelectedItems[0].SubItems[1].Text, listViewResults.SelectedItems[0].SubItems[0].Text);
            var process = new Process
            {
                EnableRaisingEvents = false,
                StartInfo = { CreateNoWindow = true, FileName = "svn.exe", Arguments = string.Format("add {0}", str), UseShellExecute = false, RedirectStandardOutput = false }
            };
            process.Start();
        }
    }
}
